/*
 * @Author: yanfeixin
 * @Date: 2025-04-15 20:35:49
 * @LastEditTime: 2025-04-21 22:02:50
 * @LastEditors: yanfeixin
 * @Description:
 */
import type { MenuTab } from '@oaexpert/layouts'
import type { Router } from 'vue-router'

// import { unref } from 'vue'
import { useDynamicRouter, useToken } from '@/hooks'
import { useBaseLayout, useMenuState } from '@oaexpert/layouts'
import { $t } from '@oaexpert/locales'

const ignoreAccess = ['/login', '/404', '/403']
const { addMenuTag } = useBaseLayout()

// 添加标志防止重复调用
let isAddingRoutes = false

export function createGenerateRouterGuard(router: Router) {
  router.beforeEach(async (to) => {
    const { getToken } = useToken()
    const token = getToken()
    if (!token && to.path !== '/login') {
      return { name: 'Login' }
    }

    if (ignoreAccess.includes(to.path)) {
      return true
    }
    const { addRouters } = useMenuState()

    // 如果路由为空且没有正在添加路由，则尝试添加路由
    if (addRouters.value.length === 0 && !isAddingRoutes) {
      const { handleAddRouter } = useDynamicRouter(router)

      try {
        isAddingRoutes = true
        const result = await handleAddRouter()

        // 如果添加路由成功，重新导航到目标路由
        if (result) {
          return { ...to }
        }
        else {
          // 如果添加路由失败（返回空数据），跳转到登录页
          console.warn('路由添加失败，跳转到登录页')
          return { name: 'Login' }
        }
      }
      catch (error) {
        console.error('添加路由时发生错误:', error)
        return { name: 'Login' }
      }
      finally {
        isAddingRoutes = false
      }
    }
    // 如果正在添加路由，等待完成
    else if (isAddingRoutes) {
      // 等待路由添加完成后再次检查
      await new Promise(resolve => setTimeout(resolve, 100))
      return { ...to }
    }
    else {
      const tab: MenuTab = {
        name: to.name as string,
        title: () => $t(to.meta.menuTitle as string),
      }
      addMenuTag(tab)
      return true
    }
  })
}
